package exsun.jt808.data.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
    /**
     * 以行为单位读取文件
     */
    public static List<String> readFileByLines(String path) {
        List<String> lines = new ArrayList<>();
        BufferedReader reader = null;
        try {
//            fileName = java.net.URLDecoder.decode(fileName, "utf-8");
            File file = new File(path);
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
            reader = new BufferedReader(isr);
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                lines.add(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return lines;
    }

    public static boolean isExist(String path) {
        File file = new File(path);
        return file.exists();
    }

   static public void writeAppendFile(String fileName,byte[] data) {
   	  if(data==null){
   	  	return;
	  }
	   try {
		   File file=new File(fileName);
		   FileOutputStream fos = null;
		   if(!file.exists()){
			   file.createNewFile();//如果文件不存在，就创建该文件
			   fos = new FileOutputStream(file);//首次写入获取
		   }else{
			   //如果文件已存在，那么就在文件末尾追加写入
			   fos = new FileOutputStream(file,true);//这里构造方法多了一个参数true,表示在文件末尾追加写入
		   }
		   fos.write(data);
		   fos.close();
	   } catch (IOException e) {
		   e.printStackTrace();
	   }
   }

    static public List<byte[]> readBytesList(String fileName, int len) {
        List<byte[]> bytesList = new ArrayList<>();
        FileInputStream fis = null;
        File file = new File(fileName);
        try {
            fis = new FileInputStream(file);
            byte[] buf = new byte[len]; //数据中转站 临时缓冲区
            int length = 0;
            //循环读取文件内容，输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
            //当文件读取到结尾时返回 -1,循环结束。
            while((length = fis.read(buf)) != -1){
                byte[] temp = new byte[length];
                System.arraycopy(buf, 0, temp, 0, temp.length);
                bytesList.add(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                fis.close();//强制关闭输入流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytesList;
    }

	static public boolean deleteFile(String fileName){
		File file=new File(fileName);
		if(file.exists()){
			return file.delete();
		}
		return true;
	}

}
